package com.example.musicplayer.configuration;

import java.io.File;
import java.io.FileNotFoundException;

import com.example.musicplayer.utils.FileUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.text.TextUtils;

public class Configuration {

    public static final String DEFAULT_SAVE_PATH = Environment.getExternalStorageDirectory().getPath()
            + "/musicplayer/download/music";

    /* SharedPreferences Keys */
    private static final String SHARE_PREFERENCE_KEY = "musicplayer_configuration";
    private static final String SHARE_PREFERENCE_KEY_SAVEPATH = "savepath";

    private String mSavePath;

    private Context mContext;

    private static Configuration sInstance;

    private Configuration(Context context) {
        mSavePath = DEFAULT_SAVE_PATH;
        this.mContext = context;
    }

    public static Configuration getInstance(Context context) {
        if (sInstance != null) {
            return sInstance;
        }

        synchronized (Configuration.class) {
            if (sInstance == null) {
                sInstance = new Configuration(context);
            }
        }

        return sInstance;
    }

    public void setSavePath(String path) throws FileNotFoundException {
        if (TextUtils.isEmpty(path)) {
            throw new IllegalArgumentException("Save path can not be empty.");
        }

        this.mSavePath = path.endsWith(File.separator) ? String.valueOf(path) : (path + File.separator);
        if (!FileUtils.createDirectory(mSavePath)) {
            throw new FileNotFoundException("savepath: " + mSavePath + " not found");
        }

        SharedPreferences sharePrefs = mContext.getSharedPreferences(SHARE_PREFERENCE_KEY, 0);
        SharedPreferences.Editor editor = sharePrefs.edit();
        editor.putString(SHARE_PREFERENCE_KEY_SAVEPATH, mSavePath);
        editor.commit();
    }

    public String getSavePath() {
        SharedPreferences sharePrefs = mContext.getSharedPreferences(SHARE_PREFERENCE_KEY, 0);
        String savepath = sharePrefs.getString(SHARE_PREFERENCE_KEY_SAVEPATH, mSavePath);
        return savepath;
    }
}
